/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity.myself;

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.FragmentStackActivity;
import cn.com.dhc.danlu.activity.LoginActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.global.DanluApplication;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.fragment.ForgetPwdFragment;
import cn.com.dhc.danlu.fragment.InputPhoneActiveFragment;
import cn.com.dhc.danlu.fragment.bridge.FragmentBridge;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.DLToolbar;
import cn.com.dhc.danlu.widget.dialog.ViewDialog;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.ForgetPwdValidateSmsCodeRequest;
import cn.com.hd.mall.web.webservices.entity.request.mydl.password.ResetPwdRequest;
import cn.com.hd.mall.web.webservices.entity.request.regist.VerificationCodeRequest;
import cn.com.hd.mall.web.webservices.entity.response.login.GetValCodeForPswResponse;
import cn.com.hd.mall.web.webservices.entity.response.login.ResetPswResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * author: 吴海洋(<a href="mailto:wuhaiyang@danlu.com">liuliqi@danlu.com</a>)<br/>
 * author: 刘立琦(<a href="mailto:liuliqi@danlu.com">liuliqi@danlu.com</a>)<br/>
 * version: 1.0.0<br/>
 * since: 2017-01-13 10:32<br/>
 *
 * <p>
 * 忘记密码相关页面--获取验证码，修改密码
 * </p>
 */
public class ForgetPwdActivity extends FragmentStackActivity implements FragmentBridge.OnFragmentBrigdeListener {
    private InputPhoneActiveFragment mActiveFragment;
    private String phoneNum;

    @Override
    public void onHandle(int type, Object obj) {
        if (type == FragmentBridge.TYPE_RESET_PWD) {
            onResetPwd((String) obj);
        } else if (type == FragmentBridge.TYPE_GET_CODE) {
            //获取短信验证码
            onForgetPwdToGetCode((String) obj);
        } else if (type == FragmentBridge.TYPE_VERIFY_CODE) {
            // 校验短信验证码
            String smsCode = (String) obj;
            ForgetPwdValidateSmsCodeRequest request = new ForgetPwdValidateSmsCodeRequest();
            request.setValCode(smsCode);

            /*add by llq*/
            agent.getApi().validateSmsCodeInForgetPwd(request).compose(OperatorUtils.defaultSchedulers())
                    .subscribe(new GeneralBusinessObserver<BaseResponse>(ForgetPwdActivity.this, R.string.tips_validate_sms_code) {
                        @Override
                        protected void onSuccess(BaseResponse baseResponse) {
                            ForgetPwdFragment forgetPwdFragment = ForgetPwdFragment.newInstance(0);
                            switchFragment(forgetPwdFragment, getResources().getString(R.string.set_new_pwd));
                            mActiveFragment.reGetSmsCode();
                        }

                        @Override
                        protected String parseBussinessException(String code) {
                            showErrorDialog(R.string.wrong_smscode);
                            return "";
                        }

                        @Override
                        protected void onAlertTips(String displayMessage) {
                            if (!TextUtils.isEmpty(displayMessage)) {
                                ToastUtil.getInstance().show(displayMessage);
                            }
                        }
                    });
        }
    }

    /**
     * 网络请求重置密码
     *
     * @param pwd
     *         新密码
     */
    public void onResetPwd(String pwd) {
        // 请求服务器重置密码  之前已经检验过验证码
        ResetPwdRequest request = new ResetPwdRequest();
        request.setTel(phoneNum);
        request.setPassword(pwd);
        request.setPasswordConfirm(pwd);
        //add by llq
        agent.getApi().resetPwd(request).compose(OperatorUtils.<ResetPswResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<ResetPswResponse>(ForgetPwdActivity.this, R.string.tips_modify_psw) {
                    @Override
                    protected void onSuccess(ResetPswResponse resetPswResponse) {
                        ViewDialog dialog = new ViewDialog.Builder(ForgetPwdActivity.this).setMessage("密码设置成功").setPositiveButton(R.string.btn_confirm, new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                skipLoginAct();
                            }
                        }).create();
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setCancelable(false);
                        dialog.show();
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        return DanluApplication.get().getString(R.string.modify_password_error_1400);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }
                });
    }

    private void skipLoginAct() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent); // 可以在intent中放入密码 在LoginActivity的onNewIntent 方法进行接受
        finish();
    }

    /**
     * 网络请求获取验证码
     *
     * @param telPhoneNum
     *         电话号码
     */
    public void onForgetPwdToGetCode(String telPhoneNum) {
        phoneNum = telPhoneNum;
        // 请求获取验证码
        VerificationCodeRequest request = new VerificationCodeRequest();
        request.setTel(phoneNum);
        //add by llq
        agent.getApi().forgetPwdGetSmsCode(request).compose(OperatorUtils.<GetValCodeForPswResponse>defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<GetValCodeForPswResponse>(ForgetPwdActivity.this, R.string.tips_get_sms_code) {
                    @Override
                    protected void onSuccess(GetValCodeForPswResponse getValCodeForPswResponse) {
                        mActiveFragment.startTimer(); //开启倒计时
                        mActiveFragment.setDisAllowInputPhone(false); //禁止输入手机号
                        ToastUtil.getInstance().show(R.string.register_tel_send_ver_code_msg);
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        String displayMsg = "";
                        switch (code) {
                            case "1":
                                displayMsg = getString(R.string.register_tel_msg);
                                mActiveFragment.reGetSmsCode();
                                break;
                            case "2":
                                showErrorDialog(R.string.no_register_phone);
                                mActiveFragment.reGetSmsCode();
                                break;
                            case "3":
                                showErrorDialog(R.string.no_active_phone);
                                mActiveFragment.reGetSmsCode();
                                break;
                            case "4":
                                displayMsg = getString(R.string.interval_lessthan);
                                mActiveFragment.reGetSmsCode();
                                break;
                            case "9":
                                displayMsg = getString(R.string.send_sms_error);
                                mActiveFragment.reGetSmsCode();
                                break;
                            default:
                                break;

                        }
                        return displayMsg;
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        mActiveFragment.reGetSmsCode();
                        ToastUtil.getInstance().show(TextUtils.isEmpty(displayMessage) ? getString(R.string.send_sms_error) : displayMessage);
                    }
                });
    }

    private void showErrorDialog(int tipId) {
        new ViewDialog.Builder(this).setMessage(tipId).setPositiveButton(R.string.btn_confirm, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create().show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_pwd);

        mToolbar = (DLToolbar) findViewById(R.id.toolbar);
        mToolbar.setBackListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popFragment();
            }
        });
        mActiveFragment = InputPhoneActiveFragment.newInstance(null);
        addDefaultFragment(mActiveFragment, "忘记密码");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}